package com.lzs.baseruku.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzs.baseruku.service.*;
import com.lzs.entity.*;
import com.lzs.util.JwtUtils;
import com.lzs.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ymx
 * @since 2020-11-25
 */
@RestController
@RequestMapping("/baseruku/receive")
@Api(value = "接货管理文档")
public class ReceiveController {
    @Autowired
    private ReceiveService receiveService;
    @Autowired
    private ReceiveDetailService receiveDetailService;
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private CommodityService commodityService;


    @ApiOperation(value = "删除时根据采购编号修改采购单状态")
    @GetMapping("/updatePurchaseByPurchaseno/{purchaseno}")
    public void updatePurchaseByPurchaseno(@PathVariable String purchaseno){

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("purchaseno",purchaseno);
        Purchase purchase = this.purchaseService.getOne(queryWrapper);
        Long id=purchase.getId();
        purchase.setState("2");

        QueryWrapper queryWrapper1=new QueryWrapper();
        queryWrapper1.eq("id",id);
        this.purchaseService.update(purchase,queryWrapper1);

    }

    @ApiOperation(value = "根据接货单号下拉所有商品名称")
    @GetMapping("/selectCommodityByReceiveno/{receiveno}")
    public R selectCommodityByReceiveno(@PathVariable String receiveno){
        QueryWrapper queryWrapper2=new QueryWrapper();
        queryWrapper2.eq("receiveno",receiveno);
        Receive receive = this.receiveService.getOne(queryWrapper2);
        String purchaseno=receive.getPurchaseno();
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("purchaseno",purchaseno);
        Purchase purchase = purchaseService.getOne(queryWrapper);
        Long id=purchase.getId();
        QueryWrapper<PurchaseDetail> queryWrapper1=new QueryWrapper();
        queryWrapper1.eq("pid",id);
        List<PurchaseDetail> purchaseDetails = this.purchaseDetailService.list(queryWrapper1);
        return R.ok().data("purchaseDetails",purchaseDetails);
    }

    @ApiOperation(value = "根据接货单号查找接货详情")
    @GetMapping("/selectReceiveDetailByReceiveno/{receiveno}")
    public R selectReceiveDetailByReceiveno(@PathVariable String receiveno){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("receiveno",receiveno);
        Receive receive = receiveService.getOne(queryWrapper);
        Long id=receive.getId();
        QueryWrapper<ReceiveDetail> queryWrapper1=new QueryWrapper();
        queryWrapper1.eq("pid",id);
        List<ReceiveDetail> receiveDetails = this.receiveDetailService.list(queryWrapper1);
        return R.ok().data("receiveDetails",receiveDetails);
    }

    @ApiOperation(value = "查询所有为录入结束的接货单号")
    @GetMapping("/selectReceiveno")
    public R selectReceiveno(){
        QueryWrapper<Receive> queryWrapper=new QueryWrapper();
        queryWrapper.eq("state","0");
        List<Receive> list = this.receiveService.list(queryWrapper);
        return R.ok().data("list",list);
    }

    @ApiOperation(value = "开始接货时修改该采购订单状态")
    @GetMapping("/updatePurchaseState/{purchaseno}")
    public R updatePurchaseState(@PathVariable String purchaseno){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("purchaseno",purchaseno);
        Purchase purchase = this.purchaseService.getOne(queryWrapper);
        purchase.setState("3");
        boolean b = this.purchaseService.update(purchase, queryWrapper);
        if (b) {
            return R.ok().message("操作成功");
        } else {
            return R.error().message("操作失败");
        }
    }

    @ApiOperation(value = "根据接货订单编号修改该订单状态")
    @GetMapping("/updateReceiveState/{receiveno}")
    public R updateReceiveState(@PathVariable String receiveno){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("receiveno",receiveno);
        Receive receive1 = this.receiveService.getOne(queryWrapper);
        receive1.setState("1");
        boolean b = this.receiveService.update(receive1, queryWrapper);
        if (b) {
            return R.ok().message("操作成功");
        } else {
            return R.error().message("操作失败");
        }
    }

    @ApiOperation(value = "查询所有已审核的采购单号")
    @GetMapping("/selectPurchaseno2")
    public R selectPurchaseno2(){
        QueryWrapper<Purchase> queryWrapper=new QueryWrapper();
        queryWrapper.eq("state","2");
        List<Purchase> list = this.purchaseService.list(queryWrapper);
        return R.ok().data("list",list);
    }

    @ApiOperation(value = "查询所有接货信息")
    @PostMapping("/selectReceive/{page}/{limit}")
    public R selectReceive(@PathVariable Integer page, @PathVariable Integer limit, @RequestBody Receive receive){
        Page<Receive> ReceivePage = receiveService.selectreceive(page, limit, receive);
        return R.ok().data("ReceivePage",ReceivePage);
    }

    @ApiOperation(value = "根据ID删除接货订单")
    @DeleteMapping("/deleteReceive/{id}")
    public R deleteReceive(@PathVariable Long id){
        Receive receive = this.receiveService.getById(id);
        if (receive.getState().equals("2")){
            return R.error().message("此订单已审核，禁止修改");
        }else {
            try{
                QueryWrapper queryWrapper=new QueryWrapper();
                queryWrapper.eq("pid",id);
                this.receiveDetailService.remove(queryWrapper);
                this.receiveService.removeById(id);
                return R.ok().message("删除成功");
            }catch (Exception e){
                return R.error().message("删除失败");
            }
        }

    }

    @ApiOperation(value = "新增或修改接货订单")
    @PostMapping("/insertOrUpdateReceive")
    public R insertOrUpdateReceive(@RequestBody Receivemore receivemore,HttpServletRequest request){


        if(receivemore.getS().substring(0,2).equals("JH")){
            return R.ok().code(20);
        }else{

            System.out.println(receivemore.getS().substring(0,1));
            String purchaseno=receivemore.getS();

            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("purchaseno",purchaseno);
            Receive receive1 = this.receiveService.getOne(queryWrapper);
            if (receive1!=null){
                return R.error().message("此采购订单已接货，不能重复接货");
            }else {
                Receive receive=new Receive();

                Date date=new Date();
                String token=request.getHeader("token");
                Long userid= JwtUtils.getMemberIdByJwtToken(token);
                User user=receiveService.selectUserByid(userid);
                String name1=user.getName();
                receive.setCreatetime(date);
                receive.setCreateid(userid);
                receive.setCreator(name1);
//                receive.setUpdator(name1);

                receive.setPurchaseno(purchaseno);
                if (receive.getId()==null){
                    receive.setState("0");
                }
                String receiveno=receivemore.getReceiveno();
                receive.setReceiveno(receiveno);
                boolean b = receiveService.saveOrUpdate(receive);
                if (b){
                    return R.ok().message("操作成功");
                }else {
                    return R.error().message("操作失败");
                }
            }
        }

    }


    @ApiOperation(value = "新增或修改接货订单")
    @PostMapping("/insertOrUpdateReceive2")
    public R insertOrUpdateReceive2(@RequestBody Receive receive){

            boolean b = receiveService.saveOrUpdate(receive);
            if (b){
                return R.ok().message("操作成功");
            }else {
                return R.error().message("操作失败");
            }
    }

    @ApiOperation(value = "根据ID查询接货订单")
    @GetMapping("/selectReceiveById/{id}")
    public R selectReceiveById(@PathVariable Long id){
        Receive receive = this.receiveService.getById(id);
        if (receive.getState().equals("2")){
            return R.error().message("此订单已审核，禁止修改");
        }else {
            return R.ok().data("receive",receive);
        }
    }

    @ApiOperation(value = "审核接货订单")
    @PostMapping("/updateState")
    public R updateState(@RequestBody List<Long> ids,HttpServletRequest request){



        for (int i=0;i<ids.size();i++){
            Receive receive = this.receiveService.getById(ids.get(i));
            if (receive.getState().equals("2")){
                return R.error().message("订单已审核，不能重复审核");
            }
            if (receive.getState().equals("0")) {
                return R.error().message("订单未录入结束，不能审核");
            }
            if (receive.getState().equals("3")) {
                return R.error().message("订单入库，不能审核");
            }
        }
        Date date=new Date();
        String token=request.getHeader("token");
        Long userid= JwtUtils.getMemberIdByJwtToken(token);
        User user=receiveService.selectUserByid(userid);
        String name1=user.getName();
        Receive receive=new Receive();
        receive.setAudittime(date);
        receive.setAuditid(userid);
        receive.setAuditor(name1);
        for (int j=0;j<ids.size();j++){
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("id",ids.get(j));
            receiveService.update(receive,queryWrapper);
        }
       return receiveService.updateState(ids,"2");
    }

    @ApiOperation(value = "撤销审核接货订单")
    @PostMapping("/NoUpdateState")
    public R NoUpdateState(@RequestBody List<Long> ids){
        for (int i=0;i<ids.size();i++){
            Receive receive = receiveService.getById(ids.get(i));
            if (receive.getState().equals("1")||receive.getState().equals("0")){
                return R.error().message("订单未审核，不能撤销审核");
            }
            if (receive.getState().equals("3")) {
                return R.error().message("订单入库，不能撤销审核");
            }
        }
        return receiveService.updateState(ids,"1");
    }

    @ApiOperation(value = "根据pid查看接货订单明细")
    @GetMapping("/LookReceiveDetailByPid/{pid}")
    public R LookReceiveDetailByPid(@PathVariable Long pid){
        QueryWrapper<ReceiveDetail> queryWrapper=new QueryWrapper();
        queryWrapper.eq("pid",pid);
        List<ReceiveDetail> receiveDetails = receiveDetailService.list(queryWrapper);
        return R.ok().data("receiveDetails",receiveDetails);
    }

    @ApiOperation(value = "查看接货订单明细")
    @GetMapping("/LookReceiveDetail/{page}/{limit}/{id}")
    public R LookReceiveDetail(@PathVariable Integer page, @PathVariable Integer limit, @PathVariable Long id){
        Page<ReceiveDetail> receiveDetails = receiveDetailService.lookReceiveDetail(page,limit,id);
        return R.ok().data("receiveDetails",receiveDetails);
    }

    @ApiOperation(value = "新增接货订单详情")
    @PostMapping("/insertReceiveDetail")
    public R insertReceiveDetail(@RequestBody ReceiveDetail receiveDetail){


        Long pid=receiveDetail.getPid();
        String bar=receiveDetail.getCommoditybar();

        QueryWrapper queryWrapper5=new QueryWrapper();
        queryWrapper5.eq("bar",bar);
        Commodity commodity1 = this.commodityService.getOne(queryWrapper5);
        String name=commodity1.getName();
        receiveDetail.setCommodityname(name);

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("bar",bar);
        Commodity commodity = this.commodityService.getOne(queryWrapper);
        Long commodityid=commodity.getId();
        Integer jieqty=receiveDetail.getQty();
        Receive receive = this.receiveService.getById(pid);
        String purchaseno=receive.getPurchaseno();
        QueryWrapper queryWrapper1=new QueryWrapper();
        queryWrapper1.eq("purchaseno",purchaseno);
        Purchase purchase = this.purchaseService.getOne(queryWrapper1);
        Long purchaseid=purchase.getId();
        QueryWrapper queryWrapper2=new QueryWrapper();
        queryWrapper2.eq("pid",purchaseid);
        queryWrapper2.eq("commodityid",commodityid);
        PurchaseDetail purchaseDetail = this.purchaseDetailService.getOne(queryWrapper2);
        Integer caiqty=purchaseDetail.getQty();
        if (jieqty>caiqty){
            return R.error().message("接货数量大于采购数量");
        }else {
            Long pid2=receiveDetail.getPid();
            String commoditybar=receiveDetail.getCommoditybar();
            Integer qty1=receiveDetail.getQty();
            QueryWrapper queryWrapper3=new QueryWrapper();
            queryWrapper3.eq("pid",pid2);
            queryWrapper3.eq("commoditybar",commoditybar);
            ReceiveDetail receiveDetail1 = this.receiveDetailService.getOne(queryWrapper3);
            if (receiveDetail1!=null){
                Integer qty0=receiveDetail1.getQty();
                Long id=receiveDetail1.getId();
                Integer qty2=qty0+qty1;
                if (qty2<=caiqty) {
                    receiveDetail1.setQty(qty2);
                    QueryWrapper queryWrapper4 = new QueryWrapper();
                    queryWrapper4.eq("id", id);
                    boolean b = this.receiveDetailService.update(receiveDetail1, queryWrapper4);
                    if (b) {
                        return R.ok().message("操作成功");
                    } else {
                        return R.error().message("操作失败");
                    }
                }else {
                    return R.error().message("数量不符");
                }
            }else {
                boolean b = receiveDetailService.save(receiveDetail);
                if (b) {
                    return R.ok().message("操作成功");
                } else {
                    return R.error().message("操作失败");
                }
            }
        }
    }

    @ApiOperation(value = "根据接货订单编号查询id")
    @GetMapping("/selectIdByReceiveno/{receiveno}")
    public R selectIdByReceiveno(@PathVariable String receiveno){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("receiveno",receiveno);
        Receive receive = this.receiveService.getOne(queryWrapper);
        return R.ok().data("receive",receive);
    }

    @ApiOperation(value = "根据采购单号下拉所有商品名称")
    @GetMapping("/selectCommodity/{purchaseno}")
    public R selectCommodity(@PathVariable String purchaseno){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("purchaseno",purchaseno);
        Purchase purchase = purchaseService.getOne(queryWrapper);
        Long id=purchase.getId();
        QueryWrapper<PurchaseDetail> queryWrapper1=new QueryWrapper();
        queryWrapper1.eq("pid",id);
        List<PurchaseDetail> purchaseDetails = this.purchaseDetailService.list(queryWrapper1);
        return R.ok().data("purchaseDetails",purchaseDetails);
    }
}

